package chn.chap.controller;

import dingyunchi.chap.entity.Sys_role;
import dingyunchi.chap.service.Sys_roleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
public class Sys_Controller {

    @Autowired
    Sys_roleService sys_roleService;

    @GetMapping("/addRole")
    public String showAddRolePage() {
        return "forward:/static/addRole.html";
    }

    @PostMapping("/saveRole")
    public String saveSys_role(@RequestBody Sys_role sys_role) {
        if (sys_role.getName() == null || sys_role.getName().trim().isEmpty()) {
            return "角色名称不能为空！";
        }

        if (sys_roleService.isNameExists(sys_role.getName())) {
            return "角色名称已存在！";
        }

        // 初始化 create_time 和 update_time
        if (sys_role.getCreate_time() == null) {
            sys_role.setCreate_time(new java.sql.Date(new Date().getTime()));
        }
        if (sys_role.getUpdate_time() == null) {
            sys_role.setUpdate_time(new java.sql.Date(new Date().getTime()));
        }

        int result = sys_roleService.saveSys_role(sys_role);
        return result > 0 ? "添加角色成功！" : "添加角色失败！";
    }

    @PostMapping("/updateSysRole")
    public String updateSysRole(@RequestBody Sys_role sys_role) {
        int result = sys_roleService.updateSys_role(sys_role);
        return result > 0 ? "修改角色成功！" : "修改角色失败！";
    }

    @GetMapping("/getAllRole")
    public List<Sys_role> getAllSys_Role() {
        return sys_roleService.getAllSys_role();
    }

    @GetMapping("/getSysRoleById/{id}")
    public Sys_role getSysRoleById(@PathVariable Integer id) {
        return sys_roleService.getSys_roleById(id);
    }

    @GetMapping("/deleteSysRoleById/{id}")
    public String deleteSysRoleById(@PathVariable Integer id) {
        int result = sys_roleService.deleteSys_role(id);
        return result > 0 ? "删除角色成功！" : "删除角色失败！";
    }
}
